package net.mimai.vultrue.bus.aop;

import net.mimai.vultrue.bus.entity.BaseItemDO;
import net.mimai.vultrue.bus.utils.EntityMyBatisUtil;
import net.mimai.vultrue.framework.utils.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.time.Instant;
import java.util.stream.Stream;

/**
 * @ClassName BizDaoAspect
 * @Description 处理父子单据范围查询的问题
 * @Author 方丈
 * @Date 2021/10/23 14:03
 * @Version 1.0.0
 **/

@Aspect
@Configuration
public class BaseItemAutoInitAspect {
    private static final Logger log = LoggerFactory.getLogger(BaseItemAutoInitAspect.class);

    @Pointcut("execution (* com.dolton..*Dao.*(..))")
    public void anyDoltonDaoMethod() {
    }

    @Pointcut("execution (* com.dolton..*Mapper.*(..))")
    public void anyDoltonMapperMethod() {
    }


    @Pointcut("@within(org.apache.ibatis.annotations.Mapper)")
    public void anyMapperMethod() {
    }

    @Around("anyDoltonDaoMethod()||anyDoltonMapperMethod()||anyMapperMethod()")
    public Object executeBizRule(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Instant now = Instant.now();
        Object result;
        String methodSignature = proceedingJoinPoint.getSignature().getName();
        try {
            Object[] args = proceedingJoinPoint.getArgs();
            Stream.of(args).filter(arg->arg instanceof BaseItemDO).forEach(arg->EntityMyBatisUtil.initBaseItemNoScope((BaseItemDO)arg));
            result = proceedingJoinPoint.proceed();
        } catch (Throwable t) {
            if (log.isErrorEnabled()) {
                log.error("Unexpected err occured at executing dao method, ", t);
            }
            throw t;
        } finally {
            if (log.isDebugEnabled()) {
                log.debug("executed {}/ms in method {}", DateTimeUtils.durationMillis(now, Instant.now()), methodSignature);
            }
        }
        return result;
    }
}
